// DriveNotes. Copyright (c) 2011, Andrei Senchuk. All rights reserved.
package net.taviscaron.drivenotes.web.core;

import net.taviscaron.drivenotes.web.forward.RequestForwarder;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.taviscaron.drivenotes.web.action.Action;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * Main servlet
 * @author Andrei Senchuk
 */
public class Controller extends HttpServlet {
    private static final Log logger = LogFactory.getLog(Controller.class);

    private ActionFactory actionFactory;

    @Override
    public void init() throws ServletException {
        super.init();
        WebApplicationContext context =
                WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
        actionFactory = (ActionFactory)context.getBean("actionFactory");
    }

    private void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String actionName = request.getParameter(Constants.ACTION_PARAM_NAME);
        Action action = actionFactory.getAction(actionName);
        if(action != null) {
            RequestForwarder forwarder = action.doAction(request, response);
            if(forwarder != null) {
                forwarder.forward(request, response);
            }
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        processRequest(request, response);
    }
}
